<template>
  <div>
    <div class="desc">
      <div class="title">1.用途：</div>
      <div class="content">
        对原生js的LocalStorage进行的封装，实现了响应式的LocalStorage
      </div>
      <el-button @click="setLocalStorage" class="el-btn">设置LocalStorage</el-button>
      <div class="title">2.合并默认值</div>
      <div class="title">2.1合并浅合并</div>
      <div class="content">设置mergeDefaults:true是浅合并</div>
      <el-button @click="mergeLocalStorage" class="el-btn">合并LocalStorage</el-button>
      <div class="title">3.自动序列化</div>
      <div class="content">
        useLocalStorage将根据提供的序列化方法。比如JSON.stringify/JSON.parse将用于对象，Number.toString/parseFloat将用于数字等。
      </div>
      <el-button @click="serializerLocalStorage" class="el-btn">序列化LocalStorage</el-button>
    </div>
  </div>
</template>
  
  <script setup lang="ts">
import { useLocalStorage } from "@vueuse/core";
const setLocalStorage = () => {
  // 响应式对象
  const state = useLocalStorage("key-store", {
    id: 100,
    url: "https://www.liu.com",
  });
  // 绑定 boolean
  const flag = useLocalStorage("key-flag", true); // returns Ref<boolean>

  // 绑定数字
  const count = useLocalStorage("key-count", 0); // returns Ref<number>
  setInterval(() => {
    state.value.id = 200;
    flag.value = false;
    // 删除本地存储
    state.value = null;
    flag.value = null;
  }, 5000);
};
const mergeLocalStorage = () => {
  localStorage.setItem("key_user", '{"id":222}');
  //用useSessionStorage绑定对象
  const userInfo = useLocalStorage(
    "key_user",
    { id: 1, url: "https://www.liu.com" },
    { mergeDefaults: true }
  );
};
const serializerLocalStorage = () => {
  const item = useLocalStorage(
    "key",
    { id: "liu" },
    {
      serializer: {
        read: (v: any) => (v ? JSON.parse(v) : null),
        write: (v: any) => JSON.stringify(v),
      },
    }
  );
};
</script>
  
  <style scoped>
.title {
  font-size: 18px;
  line-height: 60px;
  font-weight: bolder;
}
.content {
  margin-bottom: 20px;
  padding-left: 40px;
}
.el-btn {
    margin-left: 40px;
}
</style>